﻿using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.Core;

namespace Kiiro.SiteDefinition.ControlTemplates
{
    public partial class ActivityHistoryControl : KiiroUserControl
    {
        #region Public Properties

        List<ActivityHistory> histories = new List<ActivityHistory> ( );
        public List<ActivityHistory> Histories
        {
            get { return histories; }
            set { histories = value; }
        }

        public ItemType ItemType
        {
            get
            {
                if ( ViewState [ "itemType" ] != null )
                    return (ItemType) ViewState [ "itemType" ];
                return ItemType.All;
            }
            set { ViewState [ "itemType" ] = value; }
        }

        public int UserId
        {
            get
            {
                if ( ViewState [ "userId" ] != null )
                    return (int)ViewState [ "userId" ];
                return 0;
            }
            set { ViewState [ "userId" ] = value; }
        }

        public int Max
        {
            get
            {
                if ( ViewState [ "max" ] != null )
                    return (int) ViewState [ "max" ];
                return 10;
            }
            set { ViewState [ "max" ] = value; }
        }

        #endregion

        protected void Page_Load ( object sender, EventArgs e )
        {
            lnkAll.CssClass = "";
            lnkUpdates.CssClass = "";
            lnkWork.CssClass = "";
            lnkDocuments.CssClass = "";
            lnkDiscussions.CssClass = "";

            if ( !IsPostBack )
            {
                lnkAll.CssClass = "selected";
                ItemType = ItemType.All;
            }
        }

        protected override void OnPreRender ( EventArgs e )
        {
            base.OnPreRender ( e );

            string messageText = "There is no {0}activity to display";

            lnkAll.CssClass = string.Empty;
            lnkUpdates.CssClass = string.Empty;
            lnkWork.CssClass = string.Empty;
            lnkDocuments.CssClass = string.Empty;
            lnkDiscussions.CssClass = string.Empty;

            switch ( ItemType )
            {
                case ItemType.All:
                    lnkAll.CssClass = "selected";
                    messageText = string.Format ( messageText, "" );
                    break;
                case ItemType.User:
                    lnkUpdates.CssClass = "selected";
                    messageText = string.Format ( messageText, "status update " );
                    break;
                case ItemType.Task:
                case ItemType.Issue:
                    lnkWork.CssClass = "selected";
                    messageText = string.Format ( messageText, "work " );
                    break;
                case ItemType.Document:
                    lnkDocuments.CssClass = "selected";
                    messageText = string.Format ( messageText, "document " );
                    break;
                case ItemType.Discussion:
                case ItemType.Comment:
                    lnkDiscussions.CssClass = "selected";
                    messageText = string.Format ( messageText, "discussion " );
                    break;
            }

            Histories = ActivityHistoryModel.GetActivity (
                Base.SiteCollectionId, Base.ServerRelativeUrl, ItemType, Base.CurrentUser, Max, UserId );

            rptActivityStream.DataSource = Histories;
            rptActivityStream.DataBind ( );

            if ( Histories.Count > 0 )
            {
                pnlItems.Visible = true;
                pnlMoreButton.Visible = true;
                pnlMessage.Visible = false;
                litMessage.Text = string.Empty;
            }
            else
            {
                pnlItems.Visible = false;
                pnlMoreButton.Visible = false;
                pnlMessage.Visible = true;
                litMessage.Text = messageText + ( IsProject ? " for this project" : "" );
            }

            liUpdates.Visible = IsPortal;
        }

        protected void rptActivityStream_ItemDataBound ( object sender, RepeaterItemEventArgs e )
        {
            if ( e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
            {
                ActivityHistory activityHistory = ( ActivityHistory ) e.Item.DataItem;
                                
                Panel pnlItem = ( Panel ) e.Item.FindControl ( "pnlItem" );
                if ( pnlItem != null )
                {
                    if ( e.Item.ItemIndex == Histories.Count - 1 )
                    {
                        pnlItem.Style [ "border-bottom" ] = "none";
                    }
                }

                Image imgStartedBy = ( Image ) e.Item.FindControl ( "imgStartedBy" );
                if ( imgStartedBy != null )
                {
                    if ( activityHistory.CreatedBy.PictureUrl == null || string.IsNullOrEmpty ( activityHistory.CreatedBy.PictureUrl ) )
                    {
                        imgStartedBy.ImageUrl = "/_layouts/images/Kiiro/person-small.jpg";
                    }
                    else
                    {
                        imgStartedBy.ImageUrl = activityHistory.CreatedBy.PictureUrl;
                    }
                    imgStartedBy.Visible = true;
                }

                HyperLink lnkStartedBy = ( HyperLink ) e.Item.FindControl ( "lnkStartedBy" );
                if ( lnkStartedBy != null )
                {
                    lnkStartedBy.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( activityHistory.CreatedBy.FullName );
                    lnkStartedBy.NavigateUrl = String.Format ( "{0}{1}?id={2}", Base.ServerRelativeUrl, Kiiro.Common.Utility.Constants.ProjectFileUrls.UserDisplay, activityHistory.CreatedBy.SPUserId );
                }

                Literal litAction = ( Literal ) e.Item.FindControl ( "litAction" );
                Image imgAction = ( Image ) e.Item.FindControl ( "imgAction" );
                HyperLink lnkAction = ( HyperLink ) e.Item.FindControl ( "lnkAction" );
                HyperLink lnkActionProject = ( HyperLink ) e.Item.FindControl ( "lnkActionProject" );
                Literal litDiscussionCommentText = ( Literal ) e.Item.FindControl ( "litDiscussionCommentText" );

                if ( imgAction != null && litAction != null && lnkAction != null && lnkActionProject != null )
                {
                    imgAction.Visible = true;

                    Project project = null;
                    string action = null;
                    string icon = null;
                    string pageUrl = Base.ServerRelativeUrl + "/404.aspx";
                    string title = SPHelpers.ConvertHtmlToKiiroSafeText ( activityHistory.Title );
                    string imageAlt = "";
                    string discussionText = "";

                    #region Activty Type Case
                    switch ( activityHistory.ActivityItemType )
                    {
                        case ItemType.Issue:
                            if ( activityHistory.EventType == EventType.Completed )
                            {
                                action = " completed an issue: ";
                                icon = "/_layouts/images/Kiiro/icon-activity-completed.png";
                            }
                            else if ( activityHistory.EventType == EventType.Created )
                            {
                                action = " logged an issue: ";
                                icon = "/_layouts/images/Kiiro/icon-activity-issue.png";
                            }
                            else
                            {
                                action = " updated an issue: ";
                                icon = "/_layouts/images/Kiiro/icon-activity-issue.png";
                            }

                            imageAlt = "Issue";

                            if ( activityHistory.ReferencedItem != null )
                                pageUrl = SPHelpers.GetServerRelativeWebUrl ( activityHistory.SiteCollectionId, activityHistory.ServerRelativeUrl ) +
                                    Constants.ProjectFileUrls.IssueDisplay + "?id=" + activityHistory.ReferencedItem.Id;
                            break;
                        case ItemType.Task:
                            if ( activityHistory.EventType == EventType.Completed )
                            {
                                action = " completed a task: ";
                                icon = "/_layouts/images/Kiiro/icon-activity-completed.png";
                            }
                            else if ( activityHistory.EventType == EventType.Created )
                            {
                                action = " logged a task: ";
                                icon = "/_layouts/images/Kiiro/icon-activity-task.png";
                            }
                            else
                            {
                                action = " updated a task: ";
                                icon = "/_layouts/images/Kiiro/icon-activity-task.png";
                            }

                            imageAlt = "Task";

                            if ( activityHistory.ReferencedItem != null )
                                pageUrl = SPHelpers.GetServerRelativeWebUrl ( activityHistory.SiteCollectionId, activityHistory.ServerRelativeUrl ) +
                                    Constants.ProjectFileUrls.TaskDisplay + "?id=" + activityHistory.ReferencedItem.Id;
                            break;
                        case ItemType.Document:
                            if ( activityHistory.EventType == EventType.Created )
                                action = " uploaded a document: ";
                            else
                                action = " versioned a document: ";

                            icon = "/_layouts/images/Kiiro/icon-activity-document.png";

                            imageAlt = "Document";

                            if ( activityHistory.ReferencedItem != null )
                            {
                                string relUrl = SPHelpers.GetServerRelativeWebUrl ( activityHistory.SiteCollectionId, activityHistory.ServerRelativeUrl );
                                string absUrl = SPHelpers.GetHostHeader ( Request ) + relUrl;

                                Document doc = ( Document ) activityHistory.ReferencedItem;

                                bool canEdit = true;
                                if ( doc.IsProjectPlan )
                                {
                                    canEdit = Base.CurrentUser.Groups.Contains ( KiiroGroup.PortalOwner ) ||
                                        Base.CurrentUser.Groups.Contains ( KiiroGroup.ProjectOwner );
                                }

                                string extension = doc.IsFolder ? "" : doc.Title.Substring ( doc.Title.LastIndexOf ( "." ) + 1 );
                                string onclick = SPHelpers.GenerateDocumentOnClick ( absUrl + "/" + doc.Url, extension, canEdit, absUrl );

                                pageUrl = ( relUrl + "/" + activityHistory.ActivityReferenceUrl ).Replace ( "'", "%27" );
                                if ( !string.IsNullOrEmpty ( onclick ) )
                                    lnkAction.Attributes.Add ( "onclick", onclick );
                                title = SPHelpers.ConvertHtmlToKiiroSafeText ( activityHistory.ReferencedItem.Title );
                            }
                            break;
                        case ItemType.Discussion:
                        case ItemType.Comment:
                            if ( activityHistory.EventType == EventType.Created && ItemType.Discussion == activityHistory.ActivityItemType )
                                action = " started a discussion: ";
                            else
                                action = " updated a discussion: ";

                            if ( ItemType.Comment == activityHistory.ActivityItemType )
                                action = " commented on a discussion: ";

                            icon = "/_layouts/images/Kiiro/icon-activity-comment.png";

                            imageAlt = activityHistory.ActivityItemType.ToString ( );
                            
                            pageUrl = SPHelpers.GetServerRelativeWebUrl ( activityHistory.SiteCollectionId, activityHistory.ServerRelativeUrl ) +
                                Constants.ProjectFileUrls.DiscussionDisplay + "?id=" + activityHistory.ReferencedItem.Id;

                            if ( activityHistory.ReferencedItem != null )
                            {
                                if ( activityHistory.ActivityItemType == ItemType.Comment )
                                {
                                    Comment comment = ( Comment ) activityHistory.ReferencedItem;
                                    discussionText = comment.Text;

                                    if ( !string.IsNullOrEmpty ( discussionText ) )
                                    {
                                        discussionText = discussionText.Length > 250 ?
                                            discussionText.Substring ( 0, 245 ) + " ... " : discussionText;

                                        discussionText = SPHelpers.CheckTextForLinks ( discussionText );

                                        if ( activityHistory.ReferencedItem != null && comment.DiscussionId != 0 )
                                            pageUrl = SPHelpers.GetServerRelativeWebUrl ( activityHistory.SiteCollectionId, activityHistory.ServerRelativeUrl ) +
                                                Constants.ProjectFileUrls.DiscussionDisplay + "?id=" + comment.DiscussionId;
                                    }
                                }
                                else
                                {
                                    Discussion discussion = ( Discussion ) activityHistory.ReferencedItem;
                                    discussionText = !string.IsNullOrEmpty ( discussion.HTMLText ) ? discussion.HTMLText : discussion.Text;

                                    if ( !string.IsNullOrEmpty ( discussionText ) )
                                    {
                                        discussionText = discussionText.Length > 250 ?
                                            SPHelpers.Truncate ( discussionText, 250, " ... " ) : discussionText;

                                        if ( string.IsNullOrEmpty ( discussion.HTMLText ) )
                                            discussionText = SPHelpers.CheckTextForLinks ( discussionText );
                                    }
                                }
                            }

                            litDiscussionCommentText.Text = string.Format ( "<div>{0}</div>", discussionText );
                            break;

                        case ItemType.User:
                            lnkStartedBy.Text = lnkStartedBy.Text;
                            lnkAction.Visible = false;
                            action = " updated their status:";
                            imageAlt = "Status Update";
                            litDiscussionCommentText.Text = SPHelpers.CheckTextForLinks ( activityHistory.Description);
                            icon = "/_layouts/images/Kiiro/icon-activity-user.png";
                            break;
                        case ItemType.Project:
                            action = " created a " + activityHistory.ActivityItemType.ToString ( ).ToLower ( ) + ": ";
                            icon = "/_layouts/images/Kiiro/icon-activity-project.png";

                            imageAlt = "Project";

                            if ( activityHistory.ReferencedItem != null )
                            {
                                project = ( Project ) activityHistory.ReferencedItem;
                                pageUrl = project.ServerRelativeWebUrl;
                            }
                            break;
                        case ItemType.ProjectPlan:
                            action = " synchronized the project plan";
                            icon = "/_layouts/images/Kiiro/icon-activity-plan.png";

                            imageAlt = "Project Plan";

                            if ( activityHistory.ReferencedItem != null )
                            {
                                project = ( Project ) activityHistory.ReferencedItem;
                                pageUrl = "";
                            }
                            break;
                        case ItemType.CustomItem:
                            if ( !string.IsNullOrEmpty ( activityHistory.Description ) )
                                action = " created a " + activityHistory.Description.ToLower ( ) + ": ";
                            else
                                action = " created a " + activityHistory.ActivityItemType.ToString ( ).ToLower ( ) + ": ";
                            icon = "/_layouts/images/Kiiro/icon-activity-list.png";

                            imageAlt = activityHistory.Description;

                            if ( activityHistory.ReferencedItem != null )
                            {
                                CustomItem customItem = ( CustomItem ) activityHistory.ReferencedItem;
                                pageUrl = customItem.Url;
                            }
                            break;
                    }
                    #endregion

                    litAction.Text = action;
                    imgAction.ImageUrl = icon;
                    lnkAction.NavigateUrl = pageUrl;
                    lnkAction.Text = title;
                    litDiscussionCommentText.Visible = !string.IsNullOrEmpty ( litDiscussionCommentText.Text );

                    if ( SPHelpers.IsPortal ( Base.SiteCollectionId, Base.ServerRelativeUrl ) )
                    {
                        Project crossSiteProject = null;
                        if ( activityHistory.ActivityItemType != ItemType.Project && activityHistory.ActivityItemType != ItemType.User )
                        {
                            if ( project != null )
                                crossSiteProject = project;
                            else
                            {
                                string serverRelativeWebUrl = SPHelpers.GetServerRelativeWebUrl ( activityHistory.SiteCollectionId, activityHistory.ServerRelativeUrl );
                                crossSiteProject = ProjectsModel.GetByServerRelativeWebUrl ( activityHistory.SiteCollectionId, serverRelativeWebUrl );
                            }
                        }

                        if ( crossSiteProject != null )
                        {
                            Label lblActionProject = ( Label ) e.Item.FindControl ( "lblActionProject" );
                            lblActionProject.Visible = true;
                            lnkActionProject.Text = crossSiteProject.Title;
                            lnkActionProject.NavigateUrl = crossSiteProject.ServerRelativeWebUrl;
                        }
                    }
                }

                Label lblPostTime = ( Label ) e.Item.FindControl ( "lblPostTime" );
                if ( lblPostTime != null )
                {
                    int days = 0;
                    int hours = 0;
                    int minutes = 0;
                    int seconds = 0;
                    TimeSpan timeSpan = DateTime.Now.Subtract ( activityHistory.ModifiedDate );
                    days = timeSpan.Days;
                    hours = timeSpan.Hours;
                    minutes = timeSpan.Minutes;
                    seconds = timeSpan.Seconds;

                    string postTime = "{0} {1}{2} ago.";
                    
                    if ( days != 0 )
                        lblPostTime.Text = string.Format ( postTime, days, "day", days > 1 ? "s" : "" );
                    else if ( hours != 0 )
                        lblPostTime.Text = string.Format ( postTime, hours, "hour", hours > 1 ? "s" : "" );
                    else if ( minutes != 0 )
                        lblPostTime.Text = string.Format ( postTime, minutes, "minute", minutes > 1 ? "s" : "" );
                    else
                        lblPostTime.Text = string.Format ( postTime, seconds, "second", seconds > 1 ? "s" : "" );
                }
            }
        }

        protected void lnkFilter_Click ( object sender, EventArgs e )
        {
            LinkButton filter = ( LinkButton ) sender;
            if ( filter != null )
            {
                Kiiro.Common.Utility.ItemType itemType = ( ItemType ) Enum.Parse (
                    typeof ( Kiiro.Common.Utility.ItemType ), filter.CommandArgument, true );

                if ( ItemType != itemType )
                    Max = 10;

                ItemType = itemType;
            }
        }

        protected void lblMoreItems_Click ( object sender, EventArgs e )
        {
            Max += 10;
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/CONTROLTEMPLATES/Kiiro/ActivityHistoryControl.ascx.cs $
 * 
 * 46    2/08/10 5:04p Camerons
 * 
 * 45    1/25/10 1:17p Camerons
 * 
 * 44    1/21/10 5:29p Camerons
 * 
 * 43    1/18/10 1:36p Camerons
 * 
 * 42    1/15/10 1:03p Camerons
 * 
 * 41    1/15/10 9:14a Camerons
 * 
 * 40    1/13/10 1:10p Camerons
 * 
 * 39    1/12/10 12:45p Camerons
 * 
 * 38    1/12/10 12:03p Camerons
 * 
 * 37    1/11/10 12:40p Camerons
 * 
 * 36    1/11/10 12:17p Camerons
 * 
 * 35    1/11/10 11:51a Camerons
 * 
 * 34    1/08/10 4:29p Camerons
 * 
 * 33    12/18/09 10:20a Camerons
 * 
 * 32    12/17/09 5:45p Camerons
 * 
 * 31    12/17/09 5:28p Camerons
 * 
 * 30    12/11/09 1:55p Shafia
 * 
 * 29    12/11/09 11:13a Shafia
 * 
 * 28    12/07/09 2:35p Shafia
 * added a message when no items are available
 * 
 * 27    12/04/09 4:13p Shafia
 * 
 * 26    2/12/09 1:26p Shafia
 * 
 * 25    26/11/09 10:35a Camerons
 * 
 * 24    18/11/09 2:59p Camerons
 * 
 * 23    18/11/09 12:24p Camerons
 * 
 * 22    17/11/09 6:46p Camerons
 * 
 * 21    10/11/09 11:40a Camerons
 * 
 * 20    6/11/09 3:17p Camerons
 * 
 * 19    31/10/09 11:58a Camerons
 * 
 * 18    10/26/09 9:25a Adamw
 * 
 * 17    10/23/09 6:18p Adamw
 * Case 348
 * 
 * 16    23/10/09 11:07a Shafia
 * changed the condition of breaking from the loop to break when it
 * reaches 30 activity rather than two days only.
 * 
 * 15    10/19/09 7:01p Adamw
 * Case 349a, wrapped href = " instead of ' to allow for ' in filenames
 * and ripple of change
 * 
 * 14    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 13    22/09/09 6:03p Camerons
 * Code changes to support creating user on demand - version 1.1.x.x
 * 
 * 12    2/09/09 4:36p Camerons
 * Repair for GenerateDocOnClick
 * 
 * 11    31/08/09 11:56a Camerons
 * 
 * 10    26/08/09 3:11p Shafia
 * 
 * 9     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/